package com.lange.autocode.sysManager;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.core.utils.PasswordUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.lange.autocode.sysManager.service.UserServ;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/sysManager/sysUser")
public class SysUser {

    private final UserServ userServ;

    private final Dao dao;

    public SysUser(UserServ userServ, Dao dao) {
        this.userServ = userServ;
        this.dao = dao;
    }

    @RequestMapping("addUser")
    @ResponseBody
    @Transactional
    public ResultT addUser(@RequestBody JSONObject param){
        return userServ.addUser(param);
    }

    @RequestMapping("userOrgan")
    @ResponseBody
    public ResultT userOrgan(@RequestBody JSONObject param){
        JSONArray array = dao.queryJSONArray("select t1.*,t2.label,t2.code from sys_organ_users t1,sys_organ t2 where t1.org_code=t2.code and t1.username=? order by t1.org_code",param.getString("username"));
        return ResultT.success(array);
    }

    @RequestMapping("userLog")
    @ResponseBody
    public ResultT userLog(@RequestBody JSONObject param){
        JSONObject pagingData = param.getJSONObject("pagingData");
        JSONObject operData = param.getJSONObject("operData");
        String username = operData.getString("username");
        String countSql = "select count(*) from sys_user_log t1,sys_organ t2 where t1.org_code=t2.code and t1.username=?";
        dao.pageInfo(pagingData,countSql,username);
        String sql = "select t1.*,t2.label,t2.code from sys_user_log t1,sys_organ t2 where t1.org_code=t2.code and t1.username=? order by t1.date_time desc";
        JSONArray data = dao.queryJSONArrayByPage(sql,pagingData,username);

        JSONObject rs = new JSONObject();
        rs.put("pagingData",pagingData);
        rs.put("data",data);
        return ResultT.success(rs);
    }

    @RequestMapping("updateStatus")
    @ResponseBody
    @Transactional
    public ResultT updateStatus(@RequestBody JSONObject param){
        dao.executeUpdate("update sys_users set status=? where username=?",param.getString("status"),param.getString("username"));
        return ResultT.success();
    }

    @RequestMapping("batchUpdateStatus")
    @ResponseBody
    @Transactional
    public ResultT batchUpdateStatus(@RequestBody JSONObject param){
        JSONArray users = param.getJSONArray("users");
        String status = param.getString("status");
        int size = users.size();
        if(size==0){
            return ResultT.fail("没有选择要修改状态的用户");
        }

        if(StrUtil.isBlank(status)){
            return ResultT.fail("状态不能为空");
        }

        for(int i=0;i<size;i++){
            String username = users.getJSONObject(i).getString("username");
            dao.executeUpdate("update sys_users set status=? where username=?",status,username);
        }
        return ResultT.success();

    }

    @RequestMapping("updateInfo")
    @ResponseBody
    @Transactional
    public ResultT updateInfo(@RequestBody JSONObject param){
        String username=param.getString("username").trim().toUpperCase();
        //判断用户名是否存在
        JSONObject sysUser = dao.queryJSON("select * from sys_users where username=?", username);
        if(sysUser.isEmpty()){
            return ResultT.fail("用户不存在");
        }

        //邮箱、手机号格式验证
        String email = param.getString("email");
        String phone = param.getString("phone");
        if(!StrUtil.isBlank(email)){
            if(!Validator.isEmail(email.trim())){
                return ResultT.fail("邮箱地址无效！");
            }

            if(!email.trim().equals(sysUser.getString("email"))){
                int emailExists = dao.queryValue("select count(*) from sys_users where email=?",Integer.class,email.trim());
                if (emailExists>0){
                    return ResultT.fail("邮箱地址"+email+"已存在!");
                }else{
                    sysUser.put("email",email.trim());
                }
            }
        }else{
            sysUser.put("email",null);
        }

        if(!StrUtil.isBlank(phone)){
            if(!Validator.isMobile(phone.trim())){
                return ResultT.fail("手机号格式错误！");
            }
            if(!phone.trim().equals(sysUser.getString("phone"))){
                int phoneExists = dao.queryValue("select count(*) from sys_users where phone=?",Integer.class,phone);
                if (phoneExists>0){
                    return ResultT.fail("手机号"+phone+"已存在!");
                }else{
                    sysUser.put("phone",phone.trim());
                }
            }
        }else{
            sysUser.put("phone",null);
        }

        if(!param.getString("fullname").trim().equals(sysUser.getString("fullname"))){
            sysUser.put("fullname",param.getString("fullname").trim());
        }
        dao.updateJSON(sysUser,"sys_users","username");
        return ResultT.success(sysUser);
    }


    @RequestMapping("editUserOrgan")
    @ResponseBody
    @Transactional
    public ResultT editUserOrgan(@RequestBody JSONObject param){
        String username = param.getString("username");
        JSONArray orgList = param.getJSONArray("orgCode");
        List<String> currentOrgan = new ArrayList<>();
        for(int i=0;i<orgList.size();i++){
            currentOrgan.add(orgList.getJSONObject(i).getString("code"));
        }

        List<String> existsOrgan = dao.queryListValue("select org_code from sys_organ_users where username=?",String.class,username);
        //删除不存在的
        for(String orgCode:existsOrgan){
            if(!currentOrgan.contains(orgCode)){
                dao.executeUpdate("delete from sys_role_users where org_code=? and username=?",orgCode,username);
                dao.executeUpdate("delete from sys_organ_users where org_code=? and username=?",orgCode,username);
            }
        }

        List<String> defaultRole = dao.queryListValue("select id from sys_roles where is_default='Y'",String.class);

        //添加新组织机构
        for(String orgCode:currentOrgan){
            if(!existsOrgan.contains(orgCode)){
                dao.executeUpdate("insert into sys_organ_users(id,username,org_code) values(?,?,?)",IdWorker.ulid(),username,orgCode);
                for(String roleId:defaultRole){
                    dao.executeUpdate("insert into sys_role_users(id,role_id,username,org_code) values(?,?,?,?)",IdWorker.ulid(),roleId,username,orgCode);
                }
            }
        }
        return ResultT.success();
    }

    @RequestMapping("deleteUser")
    @ResponseBody
    @Transactional
    public ResultT deleteUser(@RequestBody JSONObject param){
        userServ.deleteUser(param);
        return ResultT.success();
    }

    @RequestMapping("modifySelfPwd")
    @ResponseBody
    public ResultT modifySelfPwd(@RequestBody JSONObject param) {

        if (param.getString("password").equals(param.getString("confirmPassword"))) {
            userServ.modifyPassword(UserThreadLocalUtils.getUserName(), param.getString("password"));
            return ResultT.success();
        } else {
            return ResultT.fail("两次输入密码不一致！");
        }
    }


    @RequestMapping("batchUpdateUserPassword")
    @ResponseBody
    @Transactional
    public ResultT batchUpdateUserPassword(@RequestBody JSONObject param){
        JSONArray users = param.getJSONArray("users");
        String password = param.getString("password");
        int size = users.size();
        if(size==0){
            return ResultT.fail("没有选择需要更改密码的用户");
        }

        if(StrUtil.isBlank(password)){
            return ResultT.fail("密码不能为空");
        }

        JSONObject passPolicy = dao.queryJSON("select * from autocode_pwpolicy");
        JSONObject rs = PasswordUtils.validate(passPolicy,password);
        if(rs.getIntValue("code")==0){
            return ResultT.fail(rs.getString("msg"));
        }else{
            for(int i=0;i<size;i++){
                String username = users.getJSONObject(i).getString("username");
                String hashpw = PasswordUtils.hashpw(password);
                dao.executeUpdate("update sys_users set passwrd=? where username =? ",hashpw,username);
            }
            return ResultT.success();
        }
    }

    @RequestMapping("updateUserPassword")
    @ResponseBody
    @Transactional
    public ResultT updateUserPassword(@RequestBody JSONObject param){
        String password = param.getString("password");
        String userName = param.getString("username");
        return userServ.modifyPassword(userName,password);
    }

    /**
     * 未读消息
     */
    @RequestMapping("messageWd")
    @ResponseBody
    @Transactional
    public ResultT messageWd(@RequestBody JSONObject param){
        JSONArray array = dao.queryJSONArray("select * from sys_message where username=? and status='0' order by create_time desc", UserThreadLocalUtils.getUserName());
        return ResultT.success(array);
    }

    @RequestMapping("cleanWd")
    @ResponseBody
    @Transactional
    public ResultT cleanWd(@RequestBody JSONObject param){
        dao.executeUpdate("update sys_message set status='1',read_time=? where username=? and status='0'",new Date(),UserThreadLocalUtils.getUserName());
        return ResultT.success();
    }

    @RequestMapping("setRead")
    @ResponseBody
    @Transactional
    public ResultT setRead(@RequestBody JSONObject param){
        dao.executeUpdate("update sys_message set status='1',read_time=? where id=?", new Date(),param.getString("id"));
        return ResultT.success();
    }


    @RequestMapping("delMessage")
    @ResponseBody
    @Transactional
    public ResultT delMessage(@RequestBody JSONObject param){
        dao.executeUpdate("update sys_message set status='2' where id=?",param.getString("id"));
        return ResultT.success();
    }

}
